#ifndef _FASTCGI_DETAILS_THREAD_GROUP_H_
#define _FASTCGI_DETAILS_THREAD_GROUP_H_
#include <list>
#include <thread>
#include <mutex>
#include <iterator>


namespace fastcgi
{
    class thread_group
    {
    private:
        thread_group(thread_group const&);
        thread_group& operator=(thread_group const&);
    public:
        thread_group() {}
        ~thread_group()
        {
            for(std::list<std::thread*>::iterator it=threads.begin(),end=threads.end();
                it!=end;
                ++it)
            {
                delete *it;
            }
        }

        template<typename F>
        std::thread* create_thread(F threadfunc)
        {
            std::lock_guard<std::mutex> guard(m);
            std::auto_ptr<std::thread> new_thread(new std::thread(threadfunc));
            threads.push_back(new_thread.get());
            return new_thread.release();
        }

        void add_thread(std::thread* thrd)
        {
            if(thrd)
            {
                std::lock_guard<std::mutex> guard(m);
                threads.push_back(thrd);
            }
        }

        void remove_thread(std::thread* thrd)
        {
            std::lock_guard<std::mutex> guard(m);
            std::list<std::thread*>::iterator const it=std::find(threads.begin(),threads.end(),thrd);
            if(it!=threads.end())
            {
                threads.erase(it);
            }
        }

        void join_all()
        {
            std::lock_guard<std::mutex> guard(m);

            for(std::list<std::thread*>::iterator it=threads.begin(),end=threads.end();
                it!=end;
                ++it)
            {
                (*it)->join();
            }
        }

        void interrupt_all()
        {
            std::lock_guard<std::mutex> guard(m);

            for(std::list<std::thread*>::iterator it=threads.begin(),end=threads.end();
                it!=end;
                ++it)
            {
                     if ((*it)->joinable())
	                    std::terminate();
            }
        }

        size_t size() const
        {
            std::lock_guard<std::mutex> guard(m);
            return threads.size();
        }

    private:
        std::list<std::thread*> threads;
        mutable std::mutex m;
    };
}
#endif
